package me.siphone.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hjq.http.EasyHttp;
import com.hjq.http.config.IRequestApi;
import com.hjq.http.listener.HttpCallbackProxy;
import com.tencent.mmkv.MMKV;
import java.util.ArrayList;
import java.util.List;
import me.siphone.Constants;
import me.siphone.http.api.PlayTTSApi;
import me.siphone.http.model.HttpData;
import me.siphone.view.grouptree.Device;
import me.siphone.view.grouptree.GroupTreeFragment;
import org.linphone.R;

public class TextCallFragment extends BaseFragment {

    private Button btnCall;
    private EditText etText;

    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_text_call, container, false);

        etText = view.findViewById(R.id.et_text);
        btnCall = view.findViewById(R.id.btn_call);

        etText.setText(
                MMKV.defaultMMKV().getString(Constants.CALL_TEXT_HISTORY, "山洪来了，请大家转移到安全地带!"));

        btnCall.setOnClickListener(
                v -> {
                    btnCall.setClickable(false);
                    if (getFragmentManager() != null) {
                        GroupTreeFragment fragment =
                                (GroupTreeFragment)
                                        getChildFragmentManager()
                                                .findFragmentById(R.id.group_tree_fragment);
                        List<Device> selectedDevices = fragment.getSelectedDeviceList();
                        Log.d("sisyphus", "选中设备：" + selectedDevices);
                        startTextCall(selectedDevices);
                    } else {
                        btnCall.setClickable(true);
                    }
                });

        return view;
    }

    public void startTextCall(List<Device> deviceList) {
        if (deviceList.isEmpty()) {
            Toast.makeText(getContext(), "请至少选择一个设备", Toast.LENGTH_SHORT).show();
            btnCall.setClickable(true);
            return;
        }

        String text = etText.getText().toString();
        text = text.replaceAll("\\s*", "");
        if (TextUtils.isEmpty(text)) {
            Toast.makeText(getContext(), "喊话文本不能为空", Toast.LENGTH_SHORT).show();
            btnCall.setClickable(true);
            return;
        }

        MMKV.defaultMMKV().putString(Constants.CALL_TEXT_HISTORY, text);

        List<String> numbers = new ArrayList<>();
        for (Device device : deviceList) {
            numbers.add(device.number);
        }

        String finalText = text;
        EasyHttp.post(this)
                .api(new PlayTTSApi(numbers, text))
                .request(
                        new HttpCallbackProxy<HttpData<List<String>>>(this) {
                            @Override
                            public void onHttpSuccess(@NonNull HttpData<List<String>> result) {
                                super.onHttpSuccess(result);
                                if (result.getCode() == 200 && result.getData() != null) {
                                    if (getFragmentManager() != null) {
                                        GroupTreeFragment fragment =
                                                (GroupTreeFragment)
                                                        getChildFragmentManager()
                                                                .findFragmentById(
                                                                        R.id.group_tree_fragment);
                                        fragment.clearSelected();

                                        AnswerFragment answerFragment = new AnswerFragment();
                                        Bundle data = new Bundle();
                                        data.putInt(Constants.CALL_TYPE, 1);
                                        data.putString(Constants.CALL_ID, result.getMsg());
                                        data.putString(Constants.CALL_CONTENT, finalText);
                                        data.putStringArrayList(
                                                Constants.CALL_DEVICE_IDS,
                                                (ArrayList<String>) result.getData());
                                        answerFragment.setArguments(data);
                                        getFragmentManager()
                                                .beginTransaction()
                                                .add(R.id.fl_call_container, answerFragment)
                                                .addToBackStack(
                                                        answerFragment.getClass().getSimpleName())
                                                .commit();
                                    }
                                }
                            }

                            @Override
                            public void onHttpEnd(@NonNull IRequestApi api) {
                                super.onHttpEnd(api);
                                btnCall.setClickable(true);
                            }
                        });
    }
}
